package com.itheima.service.impl;

import cn.hutool.core.convert.Convert;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.constants.BehaviorConstants;
import com.heima.model.user.dto.UserRelationDto;
import com.itheima.Utils.UserThreadLocal;
import com.itheima.service.UserRelationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

/**
 * @author yunfei
 * @date 2022年10月25日 22:07
 */
@Service
public class UserRelationServiceImpl implements UserRelationService {
    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Override
    public ResponseResult follow(UserRelationDto dto) {
        // 参数校验
        if (dto.getOperation() == null || dto.getOperation() < 0 || dto.getOperation() > 1) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        // 关注 apuser:follow:  apuser:fans:
        Integer followUserId = dto.getAuthorId();
        if (dto.getOperation() == 0) {
            // 将对方写入我的关注中
            redisTemplate.opsForZSet().add(BehaviorConstants.APUSER_FOLLOW_RELATION + UserThreadLocal.get(), Convert.toStr(followUserId), System.currentTimeMillis());
            // 将我写入对方的粉丝中
            redisTemplate.opsForZSet().add(BehaviorConstants.APUSER_FANS_RELATION + followUserId, Convert.toStr(UserThreadLocal.get()), System.currentTimeMillis());
        } else {
            // 取消关注
            redisTemplate.opsForZSet().remove(BehaviorConstants.APUSER_FOLLOW_RELATION + UserThreadLocal.get(), Convert.toStr(followUserId));
            redisTemplate.opsForZSet().remove(BehaviorConstants.APUSER_FANS_RELATION + followUserId, Convert.toStr(UserThreadLocal.get()));
        }

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}
